'use strict';
import LeeEvent from './LeeEvent.js';
import { PAGELIFETIMES } from '../constant.js';

class LeePage {
  static id = 1;
  static Page = Page;
  
  constructor(options = {}) {
    const {
      data = {},
      methods = {},
      lifetimes = {},
    } = options;
    const config = {}, event = LeeEvent.$globalEvent;
    const pageId = LeePage.id++;
    Object.assign(config, methods);
    Object.assign(config.data = {}, data);
    for (const name of PAGELIFETIMES) {
      if (lifetimes[name] === false) continue;
      config[name] = function (...args) {
        const page = this;
        event.emit(`page_${pageId}/${name}`, page, ...args);
        event.emit(`page/${name}`, page, ...args);
      };
      if (typeof lifetimes[name] === 'function') {
        event.on(`page_${pageId}/${name}`, lifetimes[name]);
      }
    }

    event.once(`page_${pageId}/onLoad`, page => {
      page.$pageId = pageId;
      page.$Event = {};
      for (const name of PAGELIFETIMES) {
        page.$Event[name] = `page_${pageId}/${name}`;
      }
    }, null, 9999);
    LeePage.Page(config);
  }
}

Page = LeePage;
